package com.exartisan.thanhdoanhn;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.exartisan.adapter.ContestAdapter;
import com.exartisan.adapter.EventDetailAdapter;
import com.exartisan.bean.Event;
import com.exartisan.bean.FbComment;
import com.exartisan.bean.Survey;
import com.exartisan.network.FacebookResponseParser;
import com.exartisan.network.FbConnnector;
import com.exartisan.network.NetworkUtility;
import com.exartisan.network.NewParamBuilder;
import com.exartisan.network.NewResponseTranslater;
import com.exartisan.network.NewRestConnector;
import com.exartisan.util.DataHolder;
import com.exartisan.util.FbUtil;
import com.exartisan.util.OnCancelAuthenticate;
import com.exartisan.util.Util;
import com.facebook.Session;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class DetailEventActivity extends Activity {

	private EventDetailAdapter mAdapter;
	private ListView listView;
	private EditText edtComment;
	private RelativeLayout btnSend;
	private boolean liked;
	private ArrayList<Survey> data;
	private int eventID;
	private ProgressBar prBarSend;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		liked = false;
		this.setContentView(R.layout.event_detail);
		listView = (ListView) findViewById(R.id.lv_eventDetail);
		btnSend = (RelativeLayout) findViewById(R.id.layout_send);
		edtComment = (EditText) findViewById(R.id.edtComment);
		prBarSend = (ProgressBar) findViewById(R.id.progressBarSend);

		btnSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (edtComment.length() < 1) {
					Toast.makeText(getBaseContext(), "Bạn chưa nhập bình luận",
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				prBarSend.setVisibility(View.VISIBLE);
				btnSend.setVisibility(View.INVISIBLE);
				FbUtil.commentOnId(edtComment.getText().toString(), DataHolder.getEvent().getFbFeedID(), getActivity(), new AsyncHttpResponseHandler(){
					
					@Override
					public void onSuccess(int arg0, String response) {
						prBarSend.setVisibility(View.GONE);
						btnSend.setVisibility(View.VISIBLE);
						Log.d("commentResponse", response.toString());
						edtComment.setText("");
						Util.hideSoftKeyboard(getActivity());
						getFbComments();
						super.onSuccess(arg0, response);
					}
					
					@Override
					public void onFailure(Throwable arg0, String arg1) {
						prBarSend.setVisibility(View.GONE);
						btnSend.setVisibility(View.VISIBLE);
						Toast.makeText(getActivity(), "Không thể đăng bình luận", Toast.LENGTH_SHORT).show();
						Log.d("commentResponse", "fail");
						super.onFailure(arg0, arg1);
					}
					
				}, new OnCancelAuthenticate() {
					
					@Override
					public void CancelAuthent() {
						prBarSend.setVisibility(View.GONE);
						btnSend.setVisibility(View.VISIBLE);
					}
				});
			}
		});
		//
		/*
		 * EventDetail detail = new EventDetail(1,
		 * "http://img3.tamtay.vn/files/photo2/2013/7/30/23/3825493/551f7e419_02c00be1_1015429_10200379224067813_884517572_o_resize.jpg"
		 * ,
		 * "http://img3.tamtay.vn/files/photo2/2013/8/1/1/1745387/951f958a8_52e45c35_image.jpg"
		 * , "22/09/2013", "vai nham", "haivl",
		 * "http://tai-facebook.net/wp-content/uploads/2013/02/avatar-facebook.jpg"
		 * ,
		 * "http://tai-facebook.net/wp-content/uploads/2013/02/avatar-facebook.jpg"
		 * , null, null); ArrayList<FbComment> fbComments = new
		 * ArrayList<FbComment>(); for (int i = 0; i < 10; i++) { FbUser fbUser
		 * = new FbUser(); fbUser.setId("12"); fbUser.setName("Van VD");
		 * fbUser.setPicture_url(
		 * "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRDIONbl8xEQo5_o16nVpO9mUxBo9bPcQ31KgEsflYXAlkl-_al"
		 * ); fbComments.add(new FbComment("232", "halo", "22/09/2013", fbUser,
		 * 0)); }
		 */
		// mAdapter = new EventDetailAdapter(detail, fbComments, this, true,
		// "http://54.243.244.187/mobile/viewevent/1");

		mAdapter = new EventDetailAdapter(DataHolder.getEvent(), this, true,
				NetworkUtility.EVENT_WEB_VIEW_URL
						+ DataHolder.getEvent().getEventID());
		listView.setAdapter(mAdapter);
		//getFbComments();
		NewRestConnector.post("", NewParamBuilder.BuildParams(NewParamBuilder.BuildDetailEventData(DataHolder.getEvent().getEventID())), new AsyncHttpResponseHandler());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
        getFbComments();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		FbUtil.logout(getBaseContext());
		return super.onOptionsItemSelected(item);
	}

	public void onClickJoin(View v) {
		final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle("Chọn cuộc thi ");
		helpBuilder.setIcon(R.drawable.icon_exam);
		LayoutInflater inflater = getLayoutInflater();
		final View PopupLayout = inflater.inflate(R.layout.popup_list_survey,
				null);
		helpBuilder.setView(PopupLayout);
		final AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();

		final ListView lvContest = (ListView) PopupLayout
				.findViewById(R.id.lv_popupSurvey);
		
		final ProgressBar pgbContest = (ProgressBar) PopupLayout.findViewById(R.id.pgbContest);
		final Button btnRetry = (Button) PopupLayout.findViewById(R.id.btnRetry);
		btnRetry.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				pgbContest.setVisibility(View.VISIBLE);
				btnRetry.setVisibility(View.GONE);
				lvContest.setVisibility(View.GONE);
				getContestData(lvContest, pgbContest, btnRetry, helpDialog);
			}
		});
		
		getContestData(lvContest, pgbContest, btnRetry, helpDialog);
		
	}
	
	private void getContestData(final ListView lvContest, final ProgressBar pgbContest, final Button btnRetry, final AlertDialog helpDialog){
		if (NetworkUtility.checkNetworkState(getActivity())) {
			eventID = (int) getIntent().getExtras().getLong("eventID");
			Log.i("eventID", eventID+"");
			NewRestConnector.post("", NewParamBuilder
					.BuildParams(NewParamBuilder.BuildSurveyData(eventID)),
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int arg0, String response) {
							if (response == null){
								pgbContest.setVisibility(View.GONE);
								btnRetry.setVisibility(View.VISIBLE);
								lvContest.setVisibility(View.GONE);
						    	return;
							}
							super.onSuccess(arg0, response);
							if (NewResponseTranslater.checkSuccess(response)) {
								data = NewResponseTranslater.getSurvey(response);
								if(data.size()==0){
									helpDialog.dismiss();
									Toast.makeText(getApplicationContext(), "Không có cuộc thi nào", Toast.LENGTH_SHORT).show();
									return;
								}
								final ContestAdapter adapter = new ContestAdapter(
										data, DetailEventActivity.this);
								lvContest.setAdapter(adapter);
								
								pgbContest.setVisibility(View.GONE);
								btnRetry.setVisibility(View.GONE);
								lvContest.setVisibility(View.VISIBLE);
								
								lvContest.setOnItemClickListener(new OnItemClickListener() {

									@Override
									public void onItemClick(AdapterView<?> mAdapter, View v, int position,
											long id) {
										getQuestionData(adapter.getSurvey(position).getSurveyID(), helpDialog);
									}
								});
							} else {
								helpDialog.dismiss();
								Toast.makeText(getApplicationContext(), "Không có cuộc thi nào", Toast.LENGTH_SHORT).show();
							}

						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							super.onFailure(arg0, arg1);
							pgbContest.setVisibility(View.GONE);
							btnRetry.setVisibility(View.VISIBLE);
							lvContest.setVisibility(View.GONE);
						}
					});
		} else {
			pgbContest.setVisibility(View.GONE);
			btnRetry.setVisibility(View.VISIBLE);
			lvContest.setVisibility(View.GONE);
			
			Toast.makeText(getActivity(), "Không có kết nối",
					Toast.LENGTH_SHORT).show();
		}
	}
	
	private void getQuestionData(final int surveyID, final AlertDialog helpDialog) {
		
		final ProgressDialog pgdialog = ProgressDialog.show(DetailEventActivity.this, "", "Đang tải đề...");
		
		if (NetworkUtility.checkNetworkState(getActivity())) {

			NewRestConnector.post("", NewParamBuilder
					.BuildParams(NewParamBuilder
							.BuildSurveyContentData(surveyID)),
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int arg0, String response) {
							if (response == null) {
								pgdialog.dismiss();
								Toast.makeText(getActivity(), "Lỗi",
										Toast.LENGTH_SHORT).show();
								return;
							}
							super.onSuccess(arg0, response);
							if (NewResponseTranslater.checkSuccess(response)) {
								pgdialog.dismiss();
								helpDialog.dismiss();
								Intent intent = new Intent(getBaseContext(),
										ExamActivity.class);
								intent.putExtra("question", response);
								intent.putExtra("surveyID", "" + surveyID);
								startActivity(intent);
							} else {
								pgdialog.dismiss();
								Toast.makeText(getActivity(), "Cuộc thi đã kết thúc",
										Toast.LENGTH_SHORT).show();
							}

						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							super.onFailure(arg0, arg1);
							pgdialog.dismiss();
							Toast.makeText(getActivity(), "Không tải được",
									Toast.LENGTH_SHORT).show();
						}
					});
		} else {
			pgdialog.dismiss();
			Toast.makeText(getActivity(), "Không có kết nối mạng",
					Toast.LENGTH_SHORT).show();
		}

	}

	public void onClickShareEvent(View v) {
		final Event event = DataHolder.getEvent();
			FbUtil.shareToFb(getActivity(), event.getEventName(),
					event.getDescription(), FbUtil.YN_LINK, event.getThumbUrl());
	}

	public void onClickLike(View v) {
		final TextView tvLikes = (TextView) findViewById(R.id.tv_CountLike);
		if(liked) {
			
			FbUtil.unLikeId(DataHolder.getEvent().getFbFeedID(), getActivity(), new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int arg0, String arg1) {
				liked = false;
				LinearLayout layoutLike = (LinearLayout) getActivity().findViewById(R.id.layoutEventLike);
				layoutLike.setBackgroundColor(Color.parseColor("#80000000"));
				Util.setLikeCount(DataHolder.getEvent().getFbFeedID(), tvLikes);
				mAdapter.notifyDataSetChanged();
				super.onSuccess(arg0, arg1);
			}
			
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				super.onFailure(arg0, arg1);
			}
			
		});
			
		} else
		FbUtil.likeId(DataHolder.getEvent().getFbFeedID(), getActivity(),
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, String response) {
						liked = true;
						LinearLayout layoutLike = (LinearLayout) findViewById(R.id.layoutEventLike);
						layoutLike.setBackgroundColor(Color.parseColor("#a0bf0000"));
						Util.setLikeCount(DataHolder.getEvent().getFbFeedID(), tvLikes);
						mAdapter.notifyDataSetChanged();
						super.onSuccess(arg0, response);
					}

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						super.onFailure(arg0, arg1);
						Util.showToast("Lỗi kết nối", getBaseContext(),
								Toast.LENGTH_SHORT);
					}
				});
	}
	
	public void onClickBack(View v){
		finish();
	}
	
	public void onClickCommentEvent(View v){
		((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
		edtComment.requestFocus();
	}
	
	public void onClickCover(View v){
		Intent i = new Intent(getActivity(), PhotoActivity.class);
		i.putExtra("type", 1);
		i.putExtra("id", DataHolder.getEvent().getEventID() );
		Log.d("detailevent", ""+DataHolder.getEvent().getEventID() );
		startActivity(i);
	}


	private void getFbComments() {
		if (NetworkUtility.checkNetworkState(getApplicationContext())) {
			// prBar.setVisibility(View.VISIBLE);
			// Log.d("feedID", event.getFbFeedID());
			// RequestParams params = new RequestParams("ids",
			// "453407711441834_458009987648273");
			FbConnnector.get(DataHolder.getEvent().getFbFeedID(),
					NetworkUtility.CONNECTION_COMMENT, new RequestParams("access_token", FbUtil.ACCESS_TOKEN),
					new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, String response) {
							// prBar.setVisibility(View.GONE);
							if (response == null) {
								Toast.makeText(getApplicationContext(),
										"Không thể tải bình luận",
										Toast.LENGTH_SHORT).show();
								return;
							}
							super.onSuccess(arg0, response);
							Log.d("fbRes", response.toString());
							ArrayList<FbComment> comments = FacebookResponseParser
									.getComments(response);
							Log.d("comments_num", comments.size() + "");
							mAdapter.setComments(comments);
							mAdapter.notifyDataSetChanged();
						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							// prBar.setVisibility(View.GONE);
							Toast.makeText(getApplicationContext(),
									"Không thể tải bình luận",
									Toast.LENGTH_SHORT).show();
							super.onFailure(arg0, arg1);
						}

					});
		} else
			Toast.makeText(this, "Không có kết nối", Toast.LENGTH_SHORT).show();
	}

	

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);

	}

	private Activity getActivity() {
		return this;
	}
	

}
